package BinarySearch.java;

public class BinarySearch {
    public static void main(String[] args) {
        int[] nums = new int[]{-1,0,3,5,9,12};
        System.out.println(search2(nums,0));
    }

    /**
     * 夹逼
     * @param nums
     * @param target
     * @return
     */
    public static int search(int[] nums, int target) {
        int p1 = 0;
        int p2 = nums.length - 1;
        while (p1 <= p2) {
            if (nums[p1] == target) {
                return p1;
            } else if (nums[p2] == target) {
                return p2;
            } else {
                p1++;
                p2--;
            }
        }
        return -1;
    }

    /**
     * 二分查找
     * @param nums
     * @param target
     * @return
     */
    public static int search2(int[] nums, int target) {
        int p1 = 0;
        int p2 = nums.length - 1;
        while (p1 <= p2) {
            int middle = (p1 + p2) / 2;
            if (nums[middle] > target) {
                p2 = middle - 1;
            } else if (nums[middle] < target) {
                p1 = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }
}
